package com.xneure.code.image;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImgTools{
	private static boolean isForcedZoom = false;
	private static boolean transparent = false;

	public BufferedImage binaryImage(BufferedImage image){
		int width = image.getWidth();
		int height = image.getHeight();
		BufferedImage grayImage = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_BINARY);
		for(int i = 0;i < width;i++){
			for(int j = 0;j < height;j++){
				int rgb = image.getRGB(i,j);
				grayImage.setRGB(i,j,rgb);
			}
		}
		return grayImage;
	}

	public BufferedImage grayImage(BufferedImage image){
		int width = image.getWidth();
		int height = image.getHeight();
		BufferedImage grayImage = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY);
		for(int i = 0;i < width;i++){
			for(int j = 0;j < height;j++){
				int rgb = image.getRGB(i,j);
				grayImage.setRGB(i,j,rgb);
			}
		}
		return grayImage;
	}

	public static BufferedImage zoom(File file,int width,int height){
		try{
			return zoom(ImageIO.read(file),width,height);
		}catch(IOException e){
			e.printStackTrace();
			return null;
		}
	}

	public static BufferedImage zoom(BufferedImage img,int width,int height){
		int srcWidth = img.getWidth();
		int srcHeight = img.getHeight();
		int dstWidth = width;// 缩略图宽度
		int dstHeight = height;// 缩略图高度
		if(srcWidth > srcHeight){
			dstHeight = (int)Math.round(height / ((double)srcWidth / srcHeight));
			dstWidth *= srcWidth / srcHeight;
		}else if(srcHeight > srcWidth){
			dstWidth = (int)Math.round(width / ((double)srcHeight / srcWidth));
		}
		// 强制缩放
		if(isForcedZoom){
			if(srcWidth < width){
				dstWidth = srcWidth;
			}
			if(srcHeight < height){
				dstHeight = srcHeight;
			}
		}
		BufferedImage _image = new BufferedImage(dstWidth,dstHeight,BufferedImage.TYPE_INT_RGB);
		// 使用透明
		if(transparent){
			_image = _image.createGraphics().getDeviceConfiguration().createCompatibleImage(dstWidth,dstHeight,Transparency.TRANSLUCENT);
		}
		Graphics graphics = _image.getGraphics();
		graphics.drawImage(img.getScaledInstance(dstWidth,dstHeight,Image.SCALE_AREA_AVERAGING),0,0,dstWidth,dstHeight,null);
		graphics.dispose();
		return _image;
	}
}
